package com.example.onlinemonitoring.comCenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.Util.LanguageManager;
import com.example.onlinemonitoring.autoRun.ComRunner;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Byqpdhistory;
import com.example.onlinemonitoring.model.Byqpdsensor;
import com.example.onlinemonitoring.model.DataFile.DataFileHeader;
import com.example.onlinemonitoring.serviceImpl.ByqpdsensorServiceImpl;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;

import java.net.SocketException;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 变压器局放
 */
@Service("byqpdCom")
@Scope("prototype")
public class ByqpdCom extends CommPortManager {
    @Autowired
    private ByqpdsensorServiceImpl byqpdserviceimpl;
    int iGispdSend =0;
    int iXYGispdSend =0;
    int ibackup =0;
    int MqttAddr = 0;
    MqttMessage mqttMessage;
    DataFileHeader dataFileHeader = new DataFileHeader();
    String MqttDT ="";
    Lock lck = new ReentrantLock();
    @Autowired
    LanguageManager languageManager;
    private String PointName ="新监测点";
    private int PointCount =1;

    private void read61850(String str) {
        Byqpdsensor currrecord = new Byqpdsensor();
        currrecord.setStationid(ad.getStationid());
        currrecord.setDevicegroup(ad.getDevicegroup());
        List<Byqpdsensor> lastrecordlist = byqpdserviceimpl.getLists(currrecord);
        if (lastrecordlist.size() != 0) {
            if (lastrecordlist.get(0).getStyle61850() != null) {
                String[] style = lastrecordlist.get(0).getStyle61850().split(",");
                for (String s : style) {
                    map61850.put(s.split("\\|")[0], s.split("\\|")[1]);
                }
            }
        }
        for (Byqpdsensor lastrecord : lastrecordlist) {
            currrecord.setDeviceaddr(lastrecord.getDeviceaddr());
            String alm = "";
            try {
                currrecord.setLastdischargetype(DischargeType[read61850IntValue(
                        String.format(isnull(map61850.get("PaDschType")), lastrecord.getDeviceaddr()))]);
                currrecord.setLastrst((long) read61850IntValue(
                        String.format(isnull(map61850.get("DschCnt")), lastrecord.getDeviceaddr())));
                currrecord.setLasttot((long) read61850IntValue(
                        String.format(isnull(map61850.get("PlsNum")), lastrecord.getDeviceaddr())));
                currrecord.setLastdischargeamount(read61850FloatValue(
                        String.format(isnull(map61850.get("AppPaDch")), lastrecord.getDeviceaddr())));
                currrecord.setLastsignalpower(
                        read61850IntValue(String.format(isnull(map61850.get("AcuPaDch")), lastrecord.getDeviceaddr())));
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("SupDevRun")), lastrecord.getDeviceaddr())) == 1 ? "运行异常,"
                                : "";
                currrecord.setLastcommunicationstatus(read61850IntValue(
                        String.format(isnull(map61850.get("MoDevConf")), lastrecord.getDeviceaddr())));
            } catch (SocketException e) {
                if (Close()) {
                    byqpdserviceimpl.UpdateStatus(ad, 1);
                    ComRunner.netmap.remove(ad.getId());
                }
            } catch (Exception e) {
                setText("读取数据出错！" + e.toString());
            }

            if (alm.equals("")) {
                currrecord.setLastalarmlevel(0);
                currrecord.setLastalarmmessage(alm);
                GetNormalAlarm("变压器局放" + lastrecord.getDeviceaddr(), lastrecord.getDevicegroup(),
                        lastrecord.getDeviceaddr(), 0,
                        lastrecord.getPointname(), "", false);
                setText("无报警");
            } else {
                currrecord.setLastalarmlevel(2);
                currrecord.setLastalarmmessage(alm);
                GetNormalAlarm("变压器局放" + lastrecord.getDeviceaddr(), lastrecord.getDevicegroup(),
                        lastrecord.getDeviceaddr(), 0,
                        lastrecord.getPointname(), alm, true);
                setText(alm);
            }

            currrecord.setLastdatatime(new Date());
            currrecord.setLasthisdatatime(addHistory(lastrecord));
            byqpdserviceimpl.Update(currrecord, false);
            StringBuilder str2 = new StringBuilder();
            str2.append("变压器局放设备返回数据： 站点号：1 地址" + currrecord.getDeviceaddr());
            str2.append("信号强度：" + currrecord.getLastsignalpower());
            str2.append("放电量：" + currrecord.getLastdischargeamount() + "pC");
            str2.append("放电量类型：" + currrecord.getLastdischargetype());
            str2.append("复位后放电次数：" + currrecord.getLastrst());
            str2.append("总放电次数：" + currrecord.getLasttot());
            setText(str2.toString());
        }
    }

    @Override
    @Transactional
    public void receiveData(String str) {
        if (ad.getCommunicationmode() == 4) {
            read61850(str);
        } else {
            byqpd(str);
        }
    }

    private void byqpd(String str) {
        str = str.toUpperCase();
        setText(str);
        if (str.length() != 66)
            return;
        String addrstr = str.substring(0, 2);
        Integer addrint = parseHex4(addrstr);

        char[] carr = HexUtil.hexString2Chars(str);
        // 信号
        int HaveSignal = carr[4] & 0x1;
        int SignalPower = carr[5] % 7 + 53;
        // 放电量
        float DischargeAmount = (carr[29] * 256 + carr[30]) / 65535f;
        // 放电类型
        int Discharge = (1 + addrint) % 4;

        // 复位后放电次数
        Long RST = (long) 0;
        int TOT = 0;
        if (carr[1] == 05) {
            DischargeAmount = (carr[29] * 256 + carr[30]);
            addrint = carr[2] * 1;
            Discharge = carr[8] * 1;
            RST = carr[6] * 256l + carr[7];
        } else {
            reSend[addrint] = 0;
            addrindex++;
        }
        String DT = DischargeType[Discharge];
        if (Language == 2)
            DT = DischargeType_eby[Discharge];
        else
            DT = DischargeType[Discharge];

        SensorData(addrint, HaveSignal, SignalPower, DischargeAmount, DT, RST, TOT);
    }

    void SensorData(Integer addrint, int HaveSignal, int SignalPower, float DischargeAmount, String DT, Long RST,
            int TOT) {
        Byqpdsensor byq = new Byqpdsensor();
        byq.setStationid(ad.getStationid());
        byq.setDevicegroup(ad.getDevicegroup());
        byq.setDeviceaddr(addrint);
        byq = byqpdserviceimpl.getModel(byq);
        if (byq == null) {

            if (Language == 2)
                setText("La base de datos actual no tiene puntos de monitoreo：" + addrint
                        + " ！ Por favor, agregue este punto de monitoreo primero.！");
            else
                setText("当前数据库无监测点：" + addrint + " ！ 请先添加该监测点！");
            return;
        }

        DischargeAmount = DischargeAmount * nto(byq.getPdkvalue()) + isnull(byq.getPdmvalue());

        if (Language == 2)
            setText("Datos devueltos del equipo de descarga parcial del transformador ：  No. de estación：1 Punto de monitorización"
                    + addrint);
        else
            setText("变压器局放设备返回数据： 站点号：1 监测点" + addrint);
        if (Language == 2)
            setText("Señal：" + HaveSignal);
        else
            setText("信号：" + HaveSignal);
        if (Language == 2)
            setText("Intensidad de la señal：" + SignalPower);
        else
            setText("信号强度：" + SignalPower);

        setText(languageManager.getLan().getDischargeAmount() + "：" + DischargeAmount + "pC");
        if (Language == 2)
            setText("Tipo de descarga de electricidad：" + DT);
        else
            setText("放电量类型：" + DT);
        if (Language == 2)
            setText("Cantidad de descargas anteriores：" + RST);
        else
            setText("复位后放电次数：" + RST);
        if (Language == 2)
            setText("Cantidad total de descargas：" + TOT);
        else
            setText("总放电次数：" + TOT);
        byq.setLasthavesignal(HaveSignal);
        byq.setLastsignalpower(SignalPower);
        String currentPath = System.getProperty("user.dir");
        String MqttfileAddr = "zjrxKGG" + MqttAddr;
        if(ad.getBrand().equals("MQTT"))
        {

            MqttAddr = addrint;
            MqttfileAddr = "zjrxKGG" + MqttAddr+"_";
            dataFileHeader.Deletefile(MqttfileAddr,currentPath + "//rixinkggjf//");
                
            if (mqttMessage != null) {
                MqttdataFile(MqttAddr, mqttMessage);
                byq.setLastdischargeamount(dataFileHeader.getDischargeSignalPeak());
                byq.setLastrst((long)dataFileHeader.getDischargecount());
                byq.setLastdischargetype(MqttDT);
            } else {
                MqttdataFile(MqttAddr,dataFileHeader.readFileToMqttMessage(currentPath + "//pds2.txt"));
                byq.setLastdischargeamount(dataFileHeader.getDischargeSignalPeak());
                byq.setLastrst((long)dataFileHeader.getDischargecount());
                byq.setLastdischargetype(MqttDT);
            }
        }
        else{
            byq.setLastdischargeamount(DischargeAmount);
            byq.setLastdischargetype(DT);
            byq.setLastrst(RST);
        }

        //if (addrint == 10 || addrint == 20)
            byq.setLasttot(RST);
        //else
        //    byq.setLasttot(isnull(byq.getLasttot()) + RST);
        byq.setLastdatatime(new Date());

        AddAndUpdate(byq);
    }

    @Transactional
    private void AddAndUpdate(Byqpdsensor record) {
        int alarmLevel = 0;// 报警等级
        String alarmMessage = "";// 报警消息
        alarmLevel = GetAlarmStatus(isnull(record.getLastdischargeamount()), isnull(record.getDischargeamountalarm()),
                isnull(record.getDischargeamountalarm()), isnull(record.getDischargeamountwarning()),
                isnull(record.getDischargeamountwarning()),
                isnull(alarmLevel), true, languageManager.getLan().getDischargeAmount(), record.getDevicegroup(),
                record.getDeviceaddr(),
                record.getPointname());
        alarmMessage += GetAlarmMessage(alarmLevel, languageManager.getLan().getDischargeAmount());
        record.setLastalarmlevel(alarmLevel);
        record.setLastalarmmessage(alarmMessage);
        record.setLastcommunicationstatus(0);
        record.setLasthisdatatime(addHistory(record));
       // lck.lock();
        if (byqpdserviceimpl.Update(record, false) == 0) {

            if (Language == 2)
                setText("Falló la actualización de los datos en tiempo real，Compruebe la conexión a la base de datos");
            else
                setText("更新实时数据失败，请检查数据库连接");
        }
       // if(ad.getBrand().equals("MQTT"))
        //MqttdataFile();
        //lck.unlock();
    }

    private Date addHistory(Byqpdsensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                    setText("lasttime:" + lasttime + "   nowtime:" + nowtime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Byqpdsensor sensor) {
        Byqpdhistory his = new Byqpdhistory();
        his.setStationid(sensor.getStationid());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setPointname(sensor.getPointname());
        his.setHavesignal(sensor.getLasthavesignal());
        his.setSignalpower(sensor.getLastsignalpower());
        his.setDischargeamount(sensor.getLastdischargeamount());
        his.setDischargetype(sensor.getLastdischargetype());
        his.setRst(sensor.getLastrst());
        his.setTot(sensor.getLasttot());
        his.setDatatime(sensor.getLastdatatime());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setMemo(sensor.getMemo());
        his.setStyle(sensor.getStyle());
        his.setInuse(sensor.getInuse());
        byqpdserviceimpl.Add(his);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        checkType = "crc16";
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmdtype = "";
        String nametype = "";
        int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        if(ad.getBrand().equals("MQTT"))
        Mqttdate(Appdevice);
        while (issend.get(Thread.currentThread().getId()) != null) {
            if (isrun) {
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                    addrindex = Appdevice.getAddrmin();
                cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                cstr = cstr + CRC16.calcCrc16(cstr);
                Send(cstr);
                if (reSend[addrindex] > 3) {
                    byqpdserviceimpl.UpdateStatus(ad, addrindex, 1);
                    reSend[addrindex] = 0;
                    addrindex++;
                }
                reSend[addrindex]++;

            } else if (rescode != 0) {
                setText(resmsg[rescode]);
            }
            Thread.sleep(timersp);
        }
    }

void Mqttdate(Appdevice appdevice)
     {
        String cstr = "";
        PointCount = appdevice.getAddrmax();
        //String HOST = "tcp://"+appdevice.getIp()+":1883";
        String HOST = "tcp://127.0.0.1:1883";
        String TOPIC = "/8E02000213012344/subnode/59425008005200300000/data_ctrl/property";
        int qos = 1;
        String clientid = "subClientkggjf";
        //String userName = "admin";
        //String passWord = "123456";
        String userName = "xyjf";
        String passWord = "xyjf321";
            // host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存

        try {
            MqttClient client = new MqttClient(HOST, clientid, new MemoryPersistence());
    
            // MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            options.setAutomaticReconnect(ON);
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(userName);
            // 设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            // 设置回调函数
            client.setCallback(new MqttCallback() {
    
                public void connectionLost(Throwable cause) {
                    setText("connectionLost");
                }
    
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("topic:"+topic);
                    System.out.println("Qos:"+message.getQos());
                    if(topic.contains("59425008005200300000")==false)
                    return;
                    iXYGispdSend++;
                    mqttMessage = message;
                    String currentPath = System.getProperty("user.dir") ;
                    if(ibackup>120)
                    {
                        dataFileHeader.DeleteAll(currentPath+"//rixinkggjfbackup//");   
                        ibackup = 0;                  
                    }
                    ibackup++;
                }
    
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------"+ token.isComplete());
                }
    
            });
            client.connect(options);
            System.out.println("connect..."+TOPIC);
            //订阅消息
            client.subscribe(TOPIC, qos);

            while (issend.get(Thread.currentThread().getId()) != null) {
            if (isrun) {
                if (addrindex > appdevice.getAddrmax() || addrindex < appdevice.getAddrmin())
                addrindex = appdevice.getAddrmin();
                cstr = String.format(appdevice.getCmd(), String.format("%02X", addrindex));
                cstr = cstr + CRC16.calcCrc16(cstr);
                Send(cstr);
                if (reSend[addrindex] > 3) {
                    byqpdserviceimpl.UpdateStatus(ad, addrindex, 1);
                 reSend[addrindex] = 0;
                 addrindex++;
                }
                reSend[addrindex]++;
                iGispdSend++;
                if(iGispdSend>(600*1000/timersp))
                {
                    if(iXYGispdSend<=2)
                    {
                        setText("shutdown\r\n"); 
                        //Runtime.getRuntime().exec("shutdown -r -t 0");
                        Runtime.getRuntime().exec("sc restart ");
                        String GatewayServicePath="D:\\GatewayService_V0.3.17_20231229\\GatewayService.exe restart";
                        Runtime.getRuntime().exec(GatewayServicePath);
                        iGispdSend=0; 
                        iXYGispdSend=0;
                       // String currentPath = System.getProperty("user.dir");
                       // MqttdataFile(dataFileHeader.readFileToMqttMessage(currentPath + "//pds2.txt"));
                    }
                    else{
                        iGispdSend=0; 
                        iXYGispdSend=0;
                    }
                }
                } else if (rescode != 0) {
                setText(resmsg[rescode]);
                }
            Thread.sleep(timersp);
            }
            client.unsubscribe(TOPIC);
            client.disconnect();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();

        }      

     
    }

    void MqttdataFile(int deviceaddr,MqttMessage message) {
        // SensorData(dataFileHeader.getDeviceaddr(), haveSignal, signalPower, dataFileHeader.getDischargeAmount(),
        //         (int) dataFileHeader.getDischargePhase(), dataFileHeader.getDT(),
        //         (long) dataFileHeader.getDischargecount(), tOT);
        String currentPath = System.getProperty("user.dir") ;
     
        //dataFileHeader.DeleteAll(currentPath+"//rixinkggjf//");
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmssSSS");
        Date currenttime = new Date();
        String formattime = sdf.format(currenttime);

        dataFileHeader.setFileGenerationTime(Long.parseLong(formattime));
        byte[] bManufacturer = new byte[32];
        String Manufacturer = String.format("%s","浙江日新电气") ;
        String Manufacturers = zerorFormat(Manufacturer,32);
        bManufacturer = Manufacturers.getBytes();
        dataFileHeader.setManufacturer(bManufacturer);
        byte[] bModel = new byte[32];
        String Model = String.format("%s","SUN-IGuard-505") ;
        String Models = zerorFormat(Model,32);
        bModel = Models.getBytes();
        dataFileHeader.setModel(bModel);
        byte[] bSerialNumber = new byte[32];
        int iSerialNumber = 1;
        //String SerialNumber = String.format("%s","S10000000000000011") ;
        //String SerialNumbers = zerorFormat(SerialNumber,32);
        //bSerialNumber = SerialNumbers.getBytes();
        //dataFileHeader.setSerialNumber(bSerialNumber);
        try {
        Random ran = new Random();
        //System.out.println("message content:"+new String(message.getPayload()));
        String msg = new String(message.getPayload());
        //JSONArray json = JSONArray.parseArray(msg);
        JSONObject jsonObject  = JSONObject.parseObject(msg);
        String id = jsonObject.getString("id");
        String version = jsonObject.getString("version");
        JSONObject params = jsonObject.getJSONObject("params");
        JSONObject status = params.getJSONObject("status");
        int battery = status.getIntValue("battery");
        JSONObject UHF = params.getJSONObject("UHF");
        //JSONObject UHF = jsonObject.getJSONObject("UHF");
        String Acqtime = UHF.getString("Acqtime");
        int phaseWindowCount = UHF.getIntValue("PhaseWindows");
        int amplitudeQuantization = UHF.getIntValue("QuantizedAmplitude");
        int powerFrequencyCycleCount = UHF.getIntValue("PowerFrequencyCycles");
        byte Unit = UHF.getByteValue("Unit");
        float MaxLimit = UHF.getFloatValue("MaxLimit");
        float MinLimit = UHF.getFloatValue("MinLimit");
        byte BandWidth = UHF.getByteValue("BandWidth");
        int AlarmLevel = UHF.getIntValue("AlarmLevel");
        int PDType = UHF.getIntValue("PDType");
        float Peak = UHF.getFloatValue("Peak");
        float Average = UHF.getFloatValue("Average");
        int DenoisingN = UHF.getIntValue("DenoisingN");
        setText("DenoisingN:"+DenoisingN);
        //if(DenoisingN>255)
        //DenoisingN=245;
        
        float MqttDischargeAmount =0;
        int MqttDischargecount =0;
        int F50 = UHF.getIntValue("F50");
        int F100 = UHF.getIntValue("F100");
        JSONArray dischargeTypeProbability = UHF.getJSONArray("PDTypeProbability");                    
        JSONArray PRPD = UHF.getJSONArray("PRPD");
        JSONArray PRPS = UHF.getJSONArray("PRPS");


        int iDT = 0,ipdt=0;
        byte[] PDTypeData = new byte[8];
        for (int i = 0; i < dischargeTypeProbability.size(); i++) {
            PDTypeData[i] = dischargeTypeProbability.getByteValue(i);
            if(iDT< PDTypeData[i])
            {
                iDT=PDTypeData[i];
                ipdt++;
            }
            }
        String DischargeType[] = { "正常","尖端放电", "悬浮放电", "沿面放电", "内部放电", "颗粒放电" , "外部干扰" , "未知局放类型" };
        MqttDT = DischargeType[ipdt];

        byte[] PRPSData = new byte[3200];
        byte[] PRPDData =  new byte[3200];
        float iDischargePhase = 0;
        float DischargePhase = 0;
        int MaxDischargeData = 0;
        int izbound = (int)(Peak - Average);
        if(izbound>10)
        izbound=10+ ran.nextInt(3);;
        //if(izbound<3)
        //izbound=3+ ran.nextInt(3);;
        int ibound = DenoisingN/10 + 1;
        int iPRPSData = 0;
        int iPRPDData = 0;
        //DischargeAmount = (byte)((Peak-Average + ran.nextInt(3))*DenoisingN/100);
        MqttDischargeAmount  = Peak + izbound; 
        if(MqttDischargeAmount>MaxLimit)
        {
            MqttDischargeAmount = MaxLimit;    
            izbound = (int)(MaxLimit - Peak);
        }

       // for (int j = 0; j < PointCount; j++) 
       {
            iSerialNumber = (deviceaddr-1)/5+1;
            String SerialNumber = String.format("%s%02d","S200000000000000",iSerialNumber) ;
            String SerialNumbers = zerorFormat(SerialNumber,32);
            bSerialNumber = SerialNumbers.getBytes();
            dataFileHeader.setSerialNumber(bSerialNumber);
            for (int i = 0; i < PRPS.size(); i++) {
                iPRPSData = PRPS.getIntValue(i);
                if(iPRPSData<=-128)
                iPRPSData=-118;
                if(iPRPSData>=128)
                iPRPSData=118;
                ByteBuffer buffer = ByteBuffer.allocate(4);
                buffer.putInt(iPRPSData);
                PRPSData[i] =buffer.get(3);
                if(MaxDischargeData<iPRPSData)
                {
                     MaxDischargeData = iPRPSData;  
                     iDischargePhase++;                             
                }

                if (iPRPSData == MaxLimit||iPRPSData<= -68) {
                    //MqttDischargeAmount = Peak ;
                } else {
                   // PRPSData[i] -= ran.nextInt(izbound);
                   iPRPSData =  iPRPSData + ran.nextInt(izbound);
                   ByteBuffer buffer1 = ByteBuffer.allocate(4);
                   buffer1.putInt(iPRPSData);
                   PRPSData[i] =buffer1.get(3);
                }
            }
            DischargePhase = (iDischargePhase%powerFrequencyCycleCount)/64*360;

        for (int i = 0; i < PRPD.size(); i++) {
            iPRPDData = PRPD.getIntValue(i);
           // PRPDData[i] = PRPD.getByteValue(i);
            if(iPRPDData==0)
            {

            }
            else
            {
                //iPRPDData +=ran.nextInt(3);
                iPRPDData = iPRPDData + ran.nextInt(3);
                ByteBuffer buffer = ByteBuffer.allocate(4);
                buffer.putInt(iPRPDData);
                PRPDData[i] =buffer.get(3);
            }
            }


            if(DenoisingN==0)
            MqttDischargecount=0;
            else
            {
                
                MqttDischargecount = DenoisingN + ran.nextInt(ibound);
            }
            
         
            Byqpdsensor byq = new Byqpdsensor();
            byq.setStationid(ad.getStationid());
            byq.setDevicegroup(ad.getDevicegroup());
            byq.setDeviceaddr(deviceaddr);
            byq = byqpdserviceimpl.getModel(byq);
            //if (byq.getInuse() == 0||byq.getLastcommunicationstatus()>0)
            //continue;
            if (byq == null) {
                
            }else{
                PointName = byq.getPointname();
               // byq.setLastdischargeamount(MqttDischargeAmount);
               // byq.setLastdischargetype(MqttDT);
                //byq.setLastrst((long)MqttDischargecount);
                //lck.lock();
                // if (byqpdserviceimpl.Update(byq, false) == 0) {

                  //   if (Language == 2)
                  //       setText("Falló la actualización de los datos en tiempo real，Compruebe la conexión a la base de datos");
                  //   else
                   //      setText("更新实时数据失败，请检查数据库连接");
                 //}
                 //lck.unlock();
            }

        iPRPSData = (int)(MqttDischargeAmount) ;
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.putInt(iPRPSData); 
        PRPSData[ran.nextInt(3200)]  = buffer.get(3);
            
        byte[] bdeviceName= new byte[118];
        //String deviceNames = String.format("%116s", ad.getName()) ;   
        String deviceName = ad.getName();
        String deviceNames = zerorFormat(deviceName,118);
        bdeviceName = deviceNames.getBytes();
        byte[] bdeviceCode= new byte[42];
        //String deviceCode ="8E02000213012344";
        String deviceCode = String.format("%d",  deviceaddr);
        String deviceCodes = zerorFormat(deviceCode,42);
        bdeviceCode = deviceCodes.getBytes();
        byte[] bmeasurementPointName= new byte[128];
        //String measurementPointName = "塑壳特高频"; 
        //String measurementPointName = String.format("%126s", PointName) ;  
        String PointNames = PointName;
        String measurementPointName = zerorFormat(PointNames,128);  
        bmeasurementPointName = measurementPointName.getBytes();
        byte[] bmeasurementPointCode= new byte[32];
        String measurementPointCode = String.format("%d", 1);
        //String measurementPointCode = String.format("%030X\0", j + 1);
        String measurementPointCodes = zerorFormat(measurementPointCode,32);
        bmeasurementPointCode = measurementPointCodes.getBytes();

        // currenttime = new Date();
        // Long lentime =currenttime.getTime();
        // lentime+=iSerialNumber*1000;
        // currenttime.setTime(lentime);
        // formattime = sdf.format(currenttime);

        //nowtime = HexUtil.todate(new Date()).getTime();
        dataFileHeader.setSpectrumGenerationTime1(Long.parseLong(formattime));
        dataFileHeader.setDeviceName1(bdeviceName);
        dataFileHeader.setDeviceCode1(bdeviceCode);
        dataFileHeader.setMeasurementPointName1(bmeasurementPointName);
        dataFileHeader.setMeasurementPointCode1(bmeasurementPointCode);
        dataFileHeader.setDataType1((byte) 1);
        dataFileHeader.setAmplitudeUnit1(Unit);
        dataFileHeader.setAmplitudeLowerLimit1(MinLimit);
        dataFileHeader.setAmplitudeUpperLimit1(MaxLimit);
        dataFileHeader.setBandwidth1(BandWidth);
        // dataFileHeader.prpdGraph.setLowerFrequency(0.5f);
        // dataFileHeader.prpdGraph.setUpperFrequency(100);
        dataFileHeader.setPhaseWindowCount1(phaseWindowCount);
        dataFileHeader.setAmplitudeQuantization1(amplitudeQuantization);
        dataFileHeader.setPowerFrequencyCycleCount1(0);
        dataFileHeader.setDischargecount1(MqttDischargecount);
        dataFileHeader.setDischargePhase1(DischargePhase);
        dataFileHeader.setDischargeTypeProbability1(PDTypeData);
        dataFileHeader.setDischargeSignalPeak1(MqttDischargeAmount);
        dataFileHeader.setDischargeSignalAverage1(Average);
        dataFileHeader.setSpectrumData1(PRPDData);

        dataFileHeader.generateprpdData(dataFileHeader,currentPath+"//rixinkggjf//"+"zjrxKGG"+(deviceaddr)+"_MONT_SPDC1_21_"+Acqtime+".dat");
        dataFileHeader.generateprpdData(dataFileHeader,currentPath+"//rixinkggjfbackup//"+"zjrxKGG"+(deviceaddr)+"_MONT_SPDC1_21_"+Acqtime+".dat");

        dataFileHeader.setSpectrumGenerationTime(Long.parseLong(formattime));
        dataFileHeader.setDeviceName(bdeviceName);
        dataFileHeader.setDeviceCode(bdeviceCode);
        dataFileHeader.setMeasurementPointName(bmeasurementPointName);
        dataFileHeader.setMeasurementPointCode(bmeasurementPointCode);
        dataFileHeader.setDataType((byte) 1);
        dataFileHeader.setAmplitudeUnit(Unit);
        dataFileHeader.setAmplitudeLowerLimit(MinLimit);
        dataFileHeader.setAmplitudeUpperLimit(MaxLimit);
        dataFileHeader.setBandwidth(BandWidth);
        // dataFileHeader.prpsGraph.setLowerFrequency(0.5f);
        // dataFileHeader.prpsGraph.setUpperFrequency(100);
        dataFileHeader.setPhaseWindowCount(phaseWindowCount);
        dataFileHeader.setAmplitudeQuantization(0);
        dataFileHeader.setPowerFrequencyCycleCount(powerFrequencyCycleCount);
        dataFileHeader.setDischargecount(MqttDischargecount);
        dataFileHeader.setDischargePhase(DischargePhase);
        dataFileHeader.setDischargeTypeProbability(PDTypeData);
        dataFileHeader.setDischargeSignalPeak(MqttDischargeAmount);
        dataFileHeader.setDischargeSignalAverage(Average);
        dataFileHeader.setSpectrumData(PRPSData);

        dataFileHeader.generateprpsData(dataFileHeader,currentPath+"//rixinkggjf//"+"zjrxKGG"+(deviceaddr)+"_MONT_SPDC1_22_"+Acqtime+".dat");
        dataFileHeader.generateprpsData(dataFileHeader,currentPath+"//rixinkggjfbackup//"+"zjrxKGG"+(deviceaddr)+"_MONT_SPDC1_22_"+Acqtime+".dat");
        }
    } catch (Exception e) {
        e.printStackTrace();

    }   
    }
}
